
*Output all census block groups

use "${Data_Clean}/panel_regdata.dta", clear

local fullgasprices "P_gas obswgtprice_lt3"
local elecprice "p_e_active"
local demog "population pop_density income"
local other_cov "fuel_economy_mean hybrid_share luxury_share mud_hh_share"

gen iou_panel = (utility_name=="Pacific Gas & Electric Company" | utility_name=="Southern California Edison" | utility_name=="San Diego Gas & Electric")

gen yearmonth = ym(year,month)
*Output all census block groups
collapse (mean) *muni iou_panel `demog' `other_cov' eiaid `elecprice' `fullgasprices' (sum) Q_BEV, by(cbg yearmonth utility_name)

preserve
keep cbg yearmonth Q_BEV `elecprice' `fullgasprices' `demog' `other_cov'
tempfile cbg_ym_data 
save `cbg_ym_data', replace
restore

collapse (mean) *muni iou_panel eiaid, by(cbg utility_name)
tempfile cbg_data 
save `cbg_data', replace



*Output list of all IOU Muni border census blocks, and all IOU Muni census blocks that used in the RD sample.
use "${Data_Clean}/spatial_RD_regdata.dta", clear
reghdfe delta_share_BEV delta_p_e_active delta_obswgtprice_lt3_, absorb(cons i.groupid#c.IOU_dist i.groupid#c.muni_dist) vce(cluster cbg0 cbg1)
gen inRDsample = e(sample)
gen muni_IOU_border_cbg = (ref_IOU==1 & adj_IOU==0) | (ref_IOU==0 & adj_IOU==1)
gen IOU_dum1 = adj_IOU
gen IOU_dum0 = ref_IOU
keep if muni_IOU_border_cbg==1
keep cbg0 cbg1 inRDsample muni_IOU_border_cbg IOU_dum0 IOU_dum1
gen index = _n

reshape long cbg IOU_dum, i(index inRDsample muni_IOU_border_cbg) j(refcbg)
bys cbg: egen inRDsample_cbg = max(inRDsample)
drop refcbg index inRDsample
duplicates drop
count

merge 1:n cbg using `cbg_data'

foreach x in inRDsample_cbg muni_IOU_border_cbg {
	replace `x' = 0 if `x' ==.
}

drop _merge
save `cbg_data', replace


use "${Data_Clean}/panel_regdata.dta", clear

local fullgasprices "obswgtprice_lt3"
local elecprice "p_e_active"
sum 

gen ym = ym(year,month)
keep `fullgasprices' `elecprice' ym cbg
keep if ym<696
local  maxlength = 48
tempfile base
save `base', replace

keep cbg ym `fullgasprices' `elecprice'
gen surv_time = .
drop if surv_time == .


forvalues x = 648/695 {
		display "`x'"
		use `base', clear
		keep if ym >= `x' & ym <=`x'+`maxlength'
		gcollapse (mean) `fullgasprices' `elecprice', by(cbg)
		gen surv_time = `maxlength'
		gen ym = `x'
		tempfile surv_time_`x'_`maxlength'
		save `surv_time_`x'_`maxlength'', replace	
}


tempfile cbg_ym_4yr
save `cbg_ym_4yr', replace emptyok

local  maxlength = 696 - 648

forvalues x = 648/695 {
		append using `surv_time_`x'_`maxlength''
}

duplicates drop

foreach x of varlist `fullgasprices' `elecprice' {
	rename `x' `x'_4yraverage
}

rename ym yearmonth
drop surv_time

save `cbg_ym_4yr', replace


/*Pull in Transaction level duration data*/

use "${Restricted_Data}/DMV/duration_data.dta", clear
gen obs=_n
tab Tech
drop if Tech~="BEV"
duplicates tag vin_anon_ID, gen(tag)

bys vin_anon_ID: egen movemean=mean(mover)
sort vin_anon_ID FullDate

gen FullDate_move = FullDate_end[_n+1] if mover[_n+1]==1 & vin_anon_ID[_n]==vin_anon_ID[_n+1]
replace FullDate_move = FullDate_end[_n+2] if mover[_n+1]==1 & mover[_n+2]==1 & vin_anon_ID[_n]==vin_anon_ID[_n+2]
replace FullDate_move = FullDate_end[_n+3] if mover[_n+1]==1 & mover[_n+2]==1  & mover[_n+3]==1 & vin_anon_ID[_n]==vin_anon_ID[_n+3]

gen moveflag = (mover[_n+1]==1 & vin_anon_ID[_n]==vin_anon_ID[_n+1])

format %td FullDate_move
order FullDate FullDate_end FullDate_move mover

drop if mover==1

gen ownership_length = FullDate_end - FullDate
replace ownership_length = FullDate_move - FullDate if moveflag==1
gen resold = ownership_length ~=.

forvalues x = 1/4 {
	gen resold_in_`x' = ownership_length<=`x'*365
}

gen year = year(FullDate)
drop if year<2010
drop if year>2017
destring cbg, force replace

gen yearmonth = ym(year(FullDate), month(FullDate))
format %tm yearmonth

/*Graphs of histograms*/

gen ownership_length_yrs = ownership_length/365
set scheme s1color
label var year "Year of Purchase"
twoway histogram ownership_length_yrs if movemean==0 & year>2013 & year<2018, by(year) freq width(.1) start(0) ///
xlabel(0 (1) 6) xtitle("Ownership Duration for Resold Vehicles (years)") xline(1 2 3 4 5, lc(gs5%10))
graph export "${ResultsOut}/Figures/yrs_of_ownership_hist.pdf", replace

gen month = month(FullDate)
set scheme s1color
label var year "Year of Purchase"
twoway histogram ownership_length_yrs if movemean==0 & year==2014 & month==1, freq width(.1) start(0) ///
xlabel(0 (1) 6) xtitle("Ownership Duration for Resold Vehicles (years)") xline(1 2 3 4 5, lc(gs5%10))
graph export "${ResultsOut}/Figures/yrs_of_ownership_hist_jan2014.pdf", replace


/*Merge in lease data*/

merge n:1 cbg year using "$Data_Clean/Experian_lease_extract_year.dta"
drop _merge
replace NewLeaseFrac=0 if NewLeaseFrac==.
replace LeaseFrac=0 if LeaseFrac==.
	
	
/* Merge in CBG data */

	merge n:1 cbg yearmonth using `cbg_ym_data'
	drop if _merge==2
	drop _merge
	merge n:1 cbg yearmonth using `cbg_ym_4yr'
	drop if _merge==2
	drop _merge
	merge n:1 cbg using `cbg_data'
	keep if _merge==3
	
	
/*Counts of overall sample*/
gen window = (year==2014 |(year==2015 & month<11))
tab window movemean

tab inRDsample_cbg if movemean==0 & window == 1
sum resold_in_4 if movemean==0 & window ==1
		
/*Regressions*/
	
egen vmindex = group(Make Model)
egen vmyindex = group(Make Model year)
egen util_fe = group(utility_name)

cap drop insample*

local gasprice "obswgtprice_lt3"
local elecprice "p_e_active"
local demog "population pop_density income"
local other_cov "fuel_economy_mean hybrid_share luxury_share mud_hh_share"
local absorb "vmindex yearmonth util_fe"
local absorbfull "vmindex yearmonth cbg"
local leasefrac "LeaseFrac"
local leasefrac ""
local addedconstraint "& movemean==0"
local ymcutoff = 668
	
	
	
estimates clear
/*Linear Probability of Resale in four years*/

reghdfe resold_in_4 `elecprice' if yearmonth <= `ymcutoff' `addedconstraint', absorb(vmindex yearmonth) vce(cluster cbg)
estadd local MMFE "X" , replace
estadd local MOPFE "X" , replace
estimates store linprob_resale4_m1a
*estadd scalar meanresale = round(r(mean),.001)

reghdfe resold_in_4 `elecprice' if yearmonth <= `ymcutoff' `addedconstraint', absorb(`absorb') vce(cluster cbg)
estadd local MMFE "X" , replace
estadd local MOPFE "X" , replace
estadd local UtilFE "X", replace
estimates store linprob_resale4_m1

reghdfe resold_in_4 `elecprice' `leasefrac' `gasprice' if yearmonth <= `ymcutoff' `addedconstraint', absorb(`absorb') vce(cluster cbg)
estadd local MMFE "X" , replace
estadd local MOPFE "X" , replace
estadd local UtilFE "X", replace
estimates store linprob_resale4_m2

reghdfe resold_in_4 `leasefrac' `elecprice' `gasprice' `demog' `other_cov' if yearmonth <= `ymcutoff' `addedconstraint', absorb(`absorb') vce(cluster cbg)
estadd local MMFE "X" , replace
estadd local MOPFE "X" , replace
estadd local UtilFE "X", replace
estadd local Demog "X", replace
estimates store linprob_resale4_m3

reghdfe resold_in_4 `leasefrac' `elecprice' `gasprice' if yearmonth <= `ymcutoff' `addedconstraint', absorb(`absorbfull') vce(cluster cbg)
estadd local MMFE "X" , replace
estadd local MOPFE "X" , replace
estadd local CBGFE "X" , replace
estimates store linprob_resale4_m4

cap label var `leasefrac' "Leased"
label var `elecprice' "Marg. Elec. Price"
label var `gasprice' "Gas Price"


local reportvars `elecprice' `gasprice'  `leasefrac' 
local modellist "linprob_resale4_m1 linprob_resale4_m2 linprob_resale4_m3 linprob_resale4_m4"
esttab `modellist' ///
	using "${ResultsOut}/Tables/resold_linprob_dmv.tex", ///
	keep(`reportvars') ///
	replace label se star(* 0.10 ** 0.05 *** 0.01) nogaps nonotes noconstant booktabs ///
	b(a2) se(a2) stats(N r2 MMFE MOPFE UtilFE Demog CBGFE,  labels("Observations" "R-Squared"  "Make-Model FE" "Purchase Mon-YR FE" "Utility FE" "Demographics" "CBG FE")) nomtitles
	
	
	
local gasprice "obswgtprice_lt3_4yraverage"
local elecprice "p_e_active_4yraverage"
cap drop insample*

reghdfe resold_in_4 `elecprice' if yearmonth <= `ymcutoff' `addedconstraint', absorb(vmindex yearmonth) vce(cluster cbg)
estadd local MMFE "X" , replace
estadd local MOPFE "X" , replace
gen insample4eleconly = e(sample)
estimates store linprob_resale4_m1a


reghdfe resold_in_4 `elecprice' if yearmonth <= `ymcutoff' `addedconstraint', absorb(`absorb') vce(cluster cbg)
estadd local MMFE "X" , replace
estadd local MOPFE "X" , replace
estadd local UtilFE "X", replace
*gen insample4eleconly = e(sample)
estimates store linprob_resale4_m1

reghdfe resold_in_4 `elecprice' `leasefrac' `gasprice' if yearmonth <= `ymcutoff' `addedconstraint', absorb(`absorb') vce(cluster cbg)
estadd local MMFE "X" , replace
estadd local MOPFE "X" , replace
estadd local UtilFE "X", replace
gen insample4elecdemo= e(sample)
estimates store linprob_resale4_m2

reghdfe resold_in_4 `leasefrac' `elecprice' `gasprice' `demog' `other_cov' if yearmonth <= `ymcutoff' `addedconstraint', absorb(`absorb') vce(cluster cbg)
estadd local MMFE "X" , replace
estadd local MOPFE "X" , replace
estadd local UtilFE "X", replace
estadd local Demog "X", replace
gen insample4elecdemolease=e(sample)
estimates store linprob_resale4_m3

reghdfe resold_in_4 `leasefrac' `elecprice' `gasprice' if yearmonth <= `ymcutoff' `addedconstraint', absorb(`absorbfull') vce(cluster cbg)
estadd local MMFE "X" , replace
estadd local MOPFE "X" , replace
estadd local CBGFE "X" , replace
estimates store linprob_resale4_m4

cap label var `leasefrac' "Leased"
label var `elecprice' "Marg. Elec. Price"
label var `gasprice' "Gas Price"



local reportvars `elecprice' `gasprice'  `leasefrac' 
esttab `modellist' ///
	using "${ResultsOut}/Tables/resold_linprob_dmv_4yr.tex", ///
	keep(`reportvars') ///
	replace label se star(* 0.10 ** 0.05 *** 0.01) nogaps nonotes noconstant booktabs ///
	b(a2) se(a2) stats(N r2 MMFE MOPFE UtilFE Demog CBGFE,  labels("Observations" "R-Squared"  "Make-Model FE" "Purchase Mon-YR FE" "Utility FE" "Demographics" "CBG FE")) nomtitles
	
	